import HttpClient from '../commons/http-client';
import {updateSupplierList, resetSupplierList} from '../reducers/supplier-list';
import {resetSupplier, updateSupplier} from '../reducers/supplier';
import {FormStatus, updateAppState} from '../reducers/app-state';
import {
  resetSupplierComment,
  updateSupplierComment,
} from '../reducers/supplier-commnet-list';

export function loadSupplierList(payload) {
  return async dispatch => {
    const info = {
      ...payload,
      page_size: 10,
      expand: 'avatar,hold_card,busy_dates,fixed_products,remv_arch_products',
    };
    const url = `/admin/vendor?${HttpClient.encodeParams(info)}`;
    const supplierListRep = await HttpClient.get(url);
    dispatch(updateSupplierList(supplierListRep.data.data));
  };
}

export function disableSupplier(payload) {
  return async (dispatch, getState) => {
    const {supplierList} = getState();
    const url = `/admin/vendor/${payload.id}`;
    const supplierRep = await HttpClient.put(url, payload);
    const supplierData = supplierRep.data.data;
    supplierList.results = supplierList.results.map(val =>
      val.id === supplierData.id ? supplierData : val,
    );
    dispatch(updateSupplierList(supplierList));
  };
}

export function reviewSupplier(payload) {
  return async dispatch => {
    const url = `/admin/vendor/${payload.id}`;
    await HttpClient.put(url, payload);
    dispatch(resetSupplierList());
  };
}

export function loadSupplier(supplierId) {
  return async dispatch => {
    const url = `/web/search-vendor/${supplierId}`;
    const SupplierRep = await HttpClient.get(url);
    const {vendor} = SupplierRep.data.data;
    dispatch(updateSupplier({...vendor}));
  };
}

export function sendEmail(id, form) {
  return async dispatch => {
    dispatch(updateAppState({formStatus: FormStatus.PENDING}));
    try {
      const url = `/web/search-vendor/${id}/send_order_mail`;
      const SupplierDetailRep = await HttpClient.post(url, form);
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}

export function loadComments(supplierId, page) {
  return async dispatch => {
    const url = `/web/search-vendor/${supplierId}/praises?page_size=10&page=${page}`;
    dispatch(resetSupplierComment());
    const commentsRep = await HttpClient.get(url);
    const {data} = commentsRep.data;
    dispatch(
      updateSupplierComment({
        total: data.count,
        results: data.results,
        current: data.current,
      }),
    );
  };
}

export function reset(payload) {
  return dispatch => {
    dispatch(resetSupplier(payload));
  };
}
